package com.vae.content.api;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vae.base.enums.CourseEnum;
import com.vae.base.enums.SystemExceptionEnum;
import com.vae.base.exception.SystemException;
import com.vae.base.model.video.RestResponse;
import com.vae.base.utils.SecurityUtil;
import com.vae.content.domain.dto.CourseBaseInfoDto;
import com.vae.content.domain.dto.CoursePreviewDto;
import com.vae.content.domain.dto.TeachplanDto;
import com.vae.content.domain.entity.CourseBase;
import com.vae.content.domain.entity.CoursePublish;
import com.vae.content.domain.entity.CoursePublishPre;
import com.vae.content.domain.entity.CourseTeacher;
import com.vae.content.service.CourseBaseService;
import com.vae.content.service.CoursePublishPreService;
import com.vae.content.service.CoursePublishService;
import com.vae.content.service.CourseTeacherService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 35238
 * 功能: 课程预览、课程提交审核、课程发布
 * 时间: 2024-05-22 21:12
 */
@Controller
public class CoursePublishController {

    @Autowired
    CoursePublishService coursePublishService;

    @Autowired
    CourseTeacherService courseTeacherService;

    @Autowired
    CourseBaseService courseBaseService;

    @Autowired
    CoursePublishPreService coursePublishPreService;


    /**
     * 课程预览
     * @param courseId
     * @return
     */
    @GetMapping("/coursepreview/{courseId}")
    public ModelAndView preview(@PathVariable("courseId") Long courseId){

        //获取课程预览信息
        CoursePreviewDto coursePreviewInfo = coursePublishService.getCoursePreviewInfo(courseId);

        //获取任课老师
        LambdaQueryWrapper<CourseTeacher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseTeacher::getCourseId,courseId);
        List<CourseTeacher> teacherList = courseTeacherService.list(wrapper);
        if (teacherList!=null) {
            coursePreviewInfo.setTeachers(teacherList);
        }

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("model",coursePreviewInfo);
        modelAndView.setViewName("course_template");
        return modelAndView;
    }

    /**
     * 课程提交审核
     * @param courseId
     */
    @ResponseBody
    @PostMapping("/courseaudit/commit/{courseId}")
    public void commitAudit(@PathVariable("courseId") Long courseId){
        SecurityUtil.XcUser user = SecurityUtil.getUser();
        Long companyId = Long.valueOf(user.getId());
        coursePublishService.commitAudit(companyId,courseId);
    }

    /**
     * 课程审核操作
     * @param courseId
     * @param auditCode
     * @return
     */
    @ResponseBody
    @Transactional
    @PostMapping ("/courseaudit/commit/{courseId}/{auditCode}")
    public RestResponse<String> auditCourse(@PathVariable("courseId") Long courseId, @PathVariable("auditCode") String auditCode){
        LambdaUpdateWrapper<CourseBase> courseBaseWrapper = new LambdaUpdateWrapper<>();
        LambdaUpdateWrapper<CoursePublishPre> coursePreWrapper = new LambdaUpdateWrapper<>();
        if ("1".equals(auditCode)) {
            //更新course_base表
            courseBaseWrapper.eq(CourseBase::getId, courseId);
            courseBaseWrapper.set(CourseBase::getAuditStatus, CourseEnum.AUDIT_STATUS_YES.getCode());
            courseBaseWrapper.set(CourseBase::getChangeDate, new Date());
            boolean update1 = courseBaseService.update(courseBaseWrapper);
            if (!update1) {
                SystemException.cast(SystemExceptionEnum.PARAMS_ERROR);
            }
            //更新course_publish_pre表
            coursePreWrapper.eq(CoursePublishPre::getId, courseId);
            coursePreWrapper.set(CoursePublishPre::getStatus, CourseEnum.AUDIT_STATUS_YES.getCode());
            coursePreWrapper.set(CoursePublishPre::getAuditDate, new Date());
            boolean update2 = coursePublishPreService.update(coursePreWrapper);
            if (!update2) {
                SystemException.cast(SystemExceptionEnum.PARAMS_ERROR);
            }
            return RestResponse.success();
        }
        if ("0".equals(auditCode)) {
            //更新course_base表
            courseBaseWrapper.eq(CourseBase::getId, courseId);
            courseBaseWrapper.set(CourseBase::getAuditStatus, CourseEnum.AUDIT_STATUS_NO.getCode());
            courseBaseWrapper.set(CourseBase::getChangeDate, new Date());
            boolean update1 = courseBaseService.update(courseBaseWrapper);
            if (!update1) {
                SystemException.cast(SystemExceptionEnum.PARAMS_ERROR);
            }
            //更新course_publish_pre表
            coursePreWrapper.eq(CoursePublishPre::getId, courseId);
            coursePreWrapper.set(CoursePublishPre::getStatus, CourseEnum.AUDIT_STATUS_NO.getCode());
            coursePreWrapper.set(CoursePublishPre::getAuditDate, new Date());
            boolean update2 = coursePublishPreService.update(coursePreWrapper);
            if (!update2) {
                SystemException.cast(SystemExceptionEnum.PARAMS_ERROR);
            }
            return RestResponse.success();
        }
        return RestResponse.validfail("参数错误，请注意提交参数的格式");
    }

    /**
     * 课程发布`
     * @param courseId
     */
    @ResponseBody
    @PostMapping ("/coursepublish/{courseId}")
    public void coursepublish(@PathVariable("courseId") Long courseId){
        SecurityUtil.XcUser user = SecurityUtil.getUser();
        Long companyId = Long.valueOf(user.getId());
        coursePublishService.publish(companyId,courseId);

    }


    /**
     * 获取课程发布信息
     * @param courseId
     * @return
     */
    @ResponseBody
    @GetMapping("/r/coursepublish/{courseId}")
    public CoursePublish getCoursepublish(@PathVariable("courseId") Long courseId) {
        CoursePublish coursePublish = coursePublishService.getCoursePublish(courseId);
        return coursePublish;
    }


    //----------------------------查询课程发布信息-马上学习-------------------------------------

    @ResponseBody
    @GetMapping("/course/whole/{courseId}")
    public CoursePreviewDto getCoursePublish(@PathVariable("courseId") Long courseId) {
        //查询缓存中的课程发布信息
        CoursePublish coursePublish = coursePublishService.getCoursePublishCache(courseId);
        if(coursePublish==null){
            return new CoursePreviewDto();
        }

        //课程基本信息
        CourseBaseInfoDto courseBase = new CourseBaseInfoDto();
        BeanUtils.copyProperties(coursePublish, courseBase);
        //课程计划
        List<TeachplanDto> teachplans = JSON.parseArray(coursePublish.getTeachplan(), TeachplanDto.class);
        CoursePreviewDto coursePreviewInfo = new CoursePreviewDto();
        coursePreviewInfo.setCourseBase(courseBase);
        coursePreviewInfo.setTeachplans(teachplans);
        return coursePreviewInfo;
    }

    //-------------------------------查询课程计划信息-------------------------------------

    @ResponseBody
    @GetMapping("/r/getTeachplanByCourseId/{courseId}")
    public Map<Integer, String> getTeachplanByCourseId(@PathVariable("courseId") Long courseId) {

        CoursePublish coursePublish = coursePublishService.getById(courseId);
        String teachplanJson = coursePublish.getTeachplan();
        Map<Integer, String> mediaIdMap = new HashMap<>();

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            List<JsonNode> teachplanList = objectMapper.readValue(teachplanJson, new TypeReference<List<JsonNode>>() {});
            for (JsonNode teachplanNode : teachplanList) {
                JsonNode teachPlanTreeNodes = teachplanNode.get("teachPlanTreeNodes");
                for (JsonNode node : teachPlanTreeNodes) {
                    int id = node.get("id").asInt();
                    String mediaId = node.get("teachplanMedia").get("mediaId").asText();
                    mediaIdMap.put(id, mediaId);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mediaIdMap;
    }

}